# coding:utf-8

from bson import ObjectId
import tornado
from tornado import gen
from tornado.web import HTTPError

from handler.api import errors
from handler.api.base import BaseHandler

import config
from data.redis import redis
from data.mongo import col_samples_01,col_vibration_leve,col_max_acceleration,col_event,col_event_data,col_StatisticsEvent24Hours,col_StatisticsEvent30Days,\
col_Tantile24Hours,col_Tantile30Days,col_Tantile7Days,col_StatisticsEvent7Days,col_event_data_mqtt,col_event_mqtt,col_level_data_mqtt

from data.mysql import mysqldb_conn

from datetime import datetime, timedelta
import json
import struct

def list_add(a,b):
    c = []
    for i in range(len(a)):
        c.append(a[i]+b[i])
    return c

#传感器编号转换函数
def transformationSensorID(sensorID):
    transformationResult=""
    ####with open('service_config_new.json', 'r') as f:
    ####    config = f.read()
    ####service_config = json.loads(config)
    ####GateWayList=service_config["GateWayList"]
    ####sensorList=[]        
    ####for item in GateWayList:
    ####    j=0
    ####    for i in item["ConnectList"]:
    ####        j+=1
    ####        if i == sensorID:
    ####            #旧传感器编号
    ####            transformationResult=item["GateWayID"]+"_0"+str(j)
                
    collectorsID = 0
    channel_id= ""
    collectorsID_str= ""
    mysqldb_conn.commit()
    mysqldb_vibration_cur = mysqldb_conn.cursor()
    mysqldb_conn.ping(reconnect=True)
    sql = " select distinct collectors_id, channel_id from cms_sensor WHERE sensor_id =  '" + sensorID + "' "
    print(sql)
    mysqldb_vibration_cur.execute(sql) 
    for row in mysqldb_vibration_cur.fetchall():
        collectorsID=row[0]
        channel_id=row[1]
    sql = "select collectors_id from cms_collectors WHERE id = " + str(collectorsID)
    print(sql)
    mysqldb_vibration_cur.execute(sql) 
    for row in mysqldb_vibration_cur.fetchall():
        collectorsID_str = row[0]
    mysqldb_vibration_cur.close()
    transformationResult = collectorsID_str.split('_')[-1]+"_"+channel_id
    return transformationResult

#计算分位置
#输入参数 旧传感器编号：sensorID，实时振级数据表名：vibration_leve_co_name, 开始时间startTime_str，结束时间：endTime_str
def tantileCount(sensorID, vibration_leve_co_name, startTime_str, endTime_str):
    #print("begin!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
    resultList=[]
    #print(sensorID)
    #print(vibration_leve_co_name)
    #print(startTime_str)
    #print(endTime_str)
    vibration_leve_data=col_vibration_leve[vibration_leve_co_name].find({"samples_time":{"$gte":startTime_str,"$lte":endTime_str}}).sort([("samples_time",1)])
    sampleList=[]
    for item_2 in vibration_leve_data:
        sampleList.append(item_2['vibration_leve'])
    vibration_leve_data.close()
    sampleListLength=len(sampleList)
    #print(sampleListLength)
    sampleList.sort(reverse=True)
    resultNumber = int( 0.01*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( "EOFError" )
        
    resultNumber = int( 0.05*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( "EOFError" )
        
    resultNumber = int( 0.1*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( "EOFError" )
    
    resultNumber = int( 0.2*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( "EOFError" )
        
    resultNumber = int( 0.3*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( "EOFError" )
        
    resultNumber = int( 0.4*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( "EOFError" )
        
    resultNumber = int( 0.5*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( "EOFError" )
    #print(resultList)
    #print("end!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
    return resultList

def findOldsensorIDbyWorkPointID(workPointID):
    OldsensorID_list=[]
    #mysqldb_conn.commit()
    mysqldb_vibration_cur = mysqldb_conn.cursor()
    mysqldb_conn.ping(reconnect=True)
    workPointName=""
    sql = "select * from cms_work where number_id = '" + workPointID + "' "
    print(sql)
    mysqldb_vibration_cur.execute(sql) 
    workPointId_list=[]
    for row in mysqldb_vibration_cur.fetchall():
        workPointId_list.append(row[0])
        workPointName=row[2]
    print(workPointId_list)    
    #依据工点ID查询采集器ID
    collectors_list = []
    collectorsID_list = []
    if len(workPointId_list) > 0:
        sql="select distinct id, collectors_id from cms_collectors WHERE work_id in ({})".format( ','.join(["%d" % item for item in workPointId_list]) )
        mysqldb_vibration_cur.execute(sql)
        #print(sql)
        for row in mysqldb_vibration_cur.fetchall():
            collectorsID_list.append(row[0])
            collectors_list.append( {"id":row[0], "collectors_id":row[1]} )
        
    #依据采集器ID查询传感器
    sensor_list = []
    if len(collectorsID_list)>0:        
        sql="select distinct id, sensor_id, sensitivity, collectors_id, channel_id from cms_sensor WHERE collectors_id in ({})".format( ','.join(["%d" % item for item in collectorsID_list]) )
        print(sql)
        mysqldb_vibration_cur.execute(sql)
        #print(sql)
        for row in mysqldb_vibration_cur.fetchall():
            sensor_list.append( {"id":row[0], "sensor_id":row[1], "sensitivity":row[2], "collectors_id":row[3], "channel_id":row[4]} )
        
    mysqldb_vibration_cur.close()
    
    #整合传感器ID
    collectorsIDs = []
    collectorsIDs_old = []
    mqtt_flag_list=[]
    mqtt_check_list=[]
    
    #with open('service_config_new.json', 'r') as f:
    #    config = f.read()
    #service_config = json.loads(config)
    #GateWayList=service_config["GateWayList"]
    #
    #for item_GateWay in GateWayList:
    #    if item_GateWay['mqtt_flag'] != 0:
    #        mqtt_flag_list.append(item_GateWay['GateWayID'])
    print("function:findOldsensorIDbyWorkPointID() sensor_list is:=================")
    print(sensor_list)
    print("function:findOldsensorIDbyWorkPointID() collectors_list is:=================")
    print(collectors_list)
    for i in range( len(sensor_list) ):
        for j in range( len(collectors_list) ):
            if str( collectors_list[j]['id'] ) == sensor_list[i]['collectors_id']:
                collectorsIDs.append( sensor_list[i]['sensor_id'] )
                temp_collectorsID = collectors_list[j]['collectors_id'].split('_')
                collectorsIDs_old.append( temp_collectorsID[-1] + "_" + sensor_list[i]['channel_id'] )
                #if temp_collectorsID[-1] in mqtt_flag_list:
                mqtt_check_list.append(1)
                #else:
                #    mqtt_check_list.append(0)
                
    
    
    collectorsID = {"collectorsIDs":collectorsIDs,
                 "collectorsIDs_old":collectorsIDs_old,
                 "mqtt_check_list":mqtt_check_list,
                 "workPointName":workPointName}
    return collectorsID

class GetSensorEventStatistics24Hours_tempHandler(BaseHandler):
    def get(self):
        sensorList=[]
        sensorID = self.get_argument('sensorID')
        print("sensorID is: "+ sensorID)
        sensorID_old = transformationSensorID(sensorID)
        print("sensorID_old is: "+ sensorID)
        print("2424242424242424242424242242424")
        print(sensorID)
        print(sensorID_old)
        samples_data=col_StatisticsEvent24Hours.find({"sensorID":sensorID,"old_SensorID":sensorID_old}).sort([("count_time",-1)]).limit(1)
        for item_2 in samples_data:
            item1={"sensorID":item_2["sensorID"],\
                 "EndTimeList":item_2["EndTimeList"],\
                 "BeginTimeList":item_2["BeginTimeList"],\
                 "peakLimitEvent":item_2["peakLimitEvent"],\
                 "vibrationLimit1Event":item_2["vibrationLimit1Event"],\
                 "vibrationLimit2Event":item_2["vibrationLimit2Event"]}
            sensorList.append(item1)
        
        samples_data.close()
        data_json = {"sensors":sensorList}
        print(data_json)
        self.write_json(data_json)


class GetSensorEventStatistics30Days_tempHandler(BaseHandler):
    def get(self):
        sensorList=[]
        sensorID = self.get_argument('sensorID')
        sensorID_old = transformationSensorID(sensorID)
        samples_data=col_StatisticsEvent30Days.find({"sensorID":sensorID,"old_SensorID":sensorID_old}).sort([("count_time",-1)]).limit(1)
        print("111111111111111111111111")
        for item_2 in samples_data:
            item1={"sensorID":item_2["sensorID"],\
                 "EndTimeList":item_2["EndTimeList"],\
                 "BeginTimeList":item_2["BeginTimeList"],\
                 "peakLimitEvent":item_2["peakLimitEvent"],\
                 "vibrationLimit1Event":item_2["vibrationLimit1Event"],\
                 "vibrationLimit2Event":item_2["vibrationLimit2Event"]}
            sensorList.append(item1)
        samples_data.close()
        data_json = {"sensors":sensorList}
        self.write_json(data_json)


class GetTantileBySensor_tempHandler(BaseHandler):
    def get(self):
        sensorID = self.get_argument('sensorID')
        sensorID_old = transformationSensorID(sensorID)
        cycleType = self.get_argument('cycleType')
        vibration_leve_co_name="vibration_leve_"+sensorID_old
        
        resultList=[]
        samples_data=col_Tantile24Hours.find({"sensorID":sensorID,"old_SensorID":sensorID_old}).sort([("count_time",-1)]).limit(1)
        endTime_str=""
        startTime_str=""
        for item_2 in samples_data:
            resultList=item_2["tantileList"]
            #resultList.append(tantileList)
            endTime_str=item_2["endTime"]
            startTime_str=item_2["startTime"]
        samples_data.close()
        
        tantileList=[]
        tantileList.append("近7天")
        
        is_exist_flag=col_Tantile7Days.count_documents({"old_SensorID":sensorID_old})
        #print("近7天:" + sensorID_old+ "is_exist_flag is:" + str(is_exist_flag))
        if is_exist_flag < 1:
            tantileList += [0,0,0,0,0,0,0]
        else:
            result_Tantile7Days = col_Tantile7Days.find({"old_SensorID":sensorID_old}).sort([("count_time",-1)]).limit(1)
            for Tantile7Days_item in result_Tantile7Days:
                tantileList += Tantile7Days_item['tantileList'][0]
                #print(tantileList)
            result_Tantile7Days.close()
        resultList.append(tantileList)
        
        tantileList=[]
        tantileList.append("近30天")
        is_exist_flag=col_Tantile30Days.count_documents({"old_SensorID":sensorID_old})            
        if is_exist_flag < 1:
            tantileList += [0,0,0,0,0,0,0]
        else:
            result_Tantile30Days = col_Tantile30Days.find({"old_SensorID":sensorID_old}).sort([("count_time",-1)]).limit(1)
            for Tantile30Days_item in result_Tantile30Days:
                tantileList += Tantile30Days_item['tantileList'][0]
            result_Tantile30Days.close()
        resultList.append(tantileList)
        
        #tantileList=[]
        #tantileList.append("近7天")
        #tantileList += [0,0,0,0,0,0,0]
        #resultList.append(tantileList)
        #tantileList=[]
        #tantileList.append("近30天")
        #tantileList += [0,0,0,0,0,0,0]
        #resultList.append(tantileList)
        
        data_json = {"tantileList":resultList,"endTime":endTime_str,"startTime":startTime_str}
        self.write_json(data_json)

class GetEventAndTantileByWorkPointID_tempHandler(BaseHandler):
    def get(self):
        resultList=[]
        workPointIDs = self.get_argument('workPointID')
        #workPointIDs="cddt5_001,gzsn_001,cddt5_002"
        cycleType = self.get_argument('cycleType')
        #print("##############################")
        #print(workPointIDs)
        #print(cycleType)
        
        workPointID_list=workPointIDs.split(",")
        #print(workPointID_list) 
        
        for WorkPointID in workPointID_list:
            result_sensorIDs = findOldsensorIDbyWorkPointID(WorkPointID)
            collectorsIDs_old_list = result_sensorIDs['collectorsIDs_old']
            collectorsIDs_list = result_sensorIDs['collectorsIDs']
            #print(collectorsIDs_old_list)
            #print(collectorsIDs_list)            
            
            count_time = ""
            for i in range(len(collectorsIDs_old_list)):
                #print(collectorsIDs_old_list[i])
                
                tantile_1=0
                tantile_5=0
                tantile_10=0
                tantile_20=0
                tantile_30=0
                tantile_40=0
                tantile_50=0     

                peakLimitEvent=0
                vibrationLimit1Event=0
                vibrationLimit2Event=0                 
                
                tantile_samples_data=""
                event_samples_data=""
                #if cycleType == "0":#按天                    
                if count_time == "":
                    if cycleType == "0":#按天  
                        tantile_samples_data=col_Tantile24Hours.find({"old_SensorID":collectorsIDs_old_list[i]}).sort([("count_time",-1)]).limit(1)
                        event_samples_data=col_StatisticsEvent24Hours.find({"old_SensorID":collectorsIDs_old_list[i]}).sort([("count_time",-1)]).limit(1)
                    if cycleType == "1":#按天  
                        tantile_samples_data=col_Tantile7Days.find({"old_SensorID":collectorsIDs_old_list[i]}).sort([("count_time",-1)]).limit(1)
                        event_samples_data=col_StatisticsEvent7Days.find({"old_SensorID":collectorsIDs_old_list[i]}).sort([("count_time",-1)]).limit(1)
                    if cycleType == "2":#按天  
                        tantile_samples_data=col_Tantile30Days.find({"old_SensorID":collectorsIDs_old_list[i]}).sort([("count_time",-1)]).limit(1)
                        event_samples_data=col_StatisticsEvent30Days.find({"old_SensorID":collectorsIDs_old_list[i]}).sort([("count_time",-1)]).limit(1)
                else:
                    if cycleType == "0":#按天  
                        tantile_samples_data=col_Tantile24Hours.find({"old_SensorID":collectorsIDs_old_list[i],"count_time":count_time}).sort([("count_time",-1)]).limit(1)
                        event_samples_data=col_StatisticsEvent24Hours.find({"old_SensorID":collectorsIDs_old_list[i],"count_time":count_time}).sort([("count_time",-1)]).limit(1)
                    if cycleType == "1":#按天  
                        tantile_samples_data=col_Tantile7Days.find({"old_SensorID":collectorsIDs_old_list[i],"count_time":count_time}).sort([("count_time",-1)]).limit(1)
                        event_samples_data=col_StatisticsEvent7Days.find({"old_SensorID":collectorsIDs_old_list[i],"count_time":count_time}).sort([("count_time",-1)]).limit(1)
                    if cycleType == "2":#按天  
                        tantile_samples_data=col_Tantile30Days.find({"old_SensorID":collectorsIDs_old_list[i],"count_time":count_time}).sort([("count_time",-1)]).limit(1)
                        event_samples_data=col_StatisticsEvent30Days.find({"old_SensorID":collectorsIDs_old_list[i],"count_time":count_time}).sort([("count_time",-1)]).limit(1)
                for item_2 in tantile_samples_data:
                    if count_time == "":
                        count_time = item_2["count_time"]
                    if cycleType == "0":#按天
                        tantile_1=item_2["tantileList"][4][1]
                        tantile_5=item_2["tantileList"][4][2]
                        tantile_10=item_2["tantileList"][4][3]
                        tantile_20=item_2["tantileList"][4][4]
                        tantile_30=item_2["tantileList"][4][5]
                        tantile_40=item_2["tantileList"][4][6]
                        tantile_50=item_2["tantileList"][4][7]
                    else:
                        tantile_1= item_2["tantileList"][0][0]
                        tantile_5= item_2["tantileList"][0][1]
                        tantile_10=item_2["tantileList"][0][2]
                        tantile_20=item_2["tantileList"][0][3]
                        tantile_30=item_2["tantileList"][0][4]
                        tantile_40=item_2["tantileList"][0][5]
                        tantile_50=item_2["tantileList"][0][6]

                               
                
                for item_3 in event_samples_data: 
                    peakLimitEvent+=sum(item_3["peakLimitEvent"])
                    vibrationLimit1Event+=sum(item_3["vibrationLimit1Event"])
                    vibrationLimit2Event+=sum(item_3["vibrationLimit2Event"])
                if isinstance(tantile_samples_data,str):
                    tantile_samples_data = ""
                else:
                    tantile_samples_data.close()
                if isinstance(event_samples_data,str):
                    event_samples_data = ""
                else:
                    event_samples_data.close()
                         
                item1={"sensorID":collectorsIDs_list[i],\
                     "peakLimitCount":peakLimitEvent,\
                     "vibrationLimit1":vibrationLimit1Event,\
                     "vibrationLimit2":vibrationLimit2Event,\
                     "tantile_1":tantile_1,"tantile_5":tantile_5,"tantile_10":tantile_10,\
                     "tantile_20":tantile_20,"tantile_30":tantile_30,"tantile_40":tantile_40,\
                     "tantile_50":tantile_50}
                
                resultList.append(item1)
                #print(item1)
        #print(resultList)
        data_json = {"tantileList":resultList}
        self.write_json(data_json)

def GetWorkPointEventNumber4Cycle(workPointID_list, cycleType):
    resultList=[]
    for WorkPointID in workPointID_list:
            result_sensorIDs = findOldsensorIDbyWorkPointID(WorkPointID)
            collectorsIDs_old_list = result_sensorIDs['collectorsIDs_old']
            print(collectorsIDs_old_list)
            
            count_time = ""
            EndTimeList=[]
            BeginTimeList=[]
            peakLimitEvent=[]
            vibrationLimit1Event=[]
            vibrationLimit2Event=[]
            
            no_data_flag = 1
            
            for i in range(len(collectorsIDs_old_list)):
                print(collectorsIDs_old_list[i])
                samples_data=""
                #if cycleType == "0":#按天                    
                if count_time == "":
                    if cycleType == "0":#按天  
                        samples_data=col_StatisticsEvent24Hours.find({"old_SensorID":collectorsIDs_old_list[i]}).sort([("count_time",-1)]).limit(1)
                    if cycleType == "1":#按天  
                        samples_data=col_StatisticsEvent7Days.find({"old_SensorID":collectorsIDs_old_list[i]}).sort([("count_time",-1)]).limit(1)
                    if cycleType == "2":#按天  
                        samples_data=col_StatisticsEvent30Days.find({"old_SensorID":collectorsIDs_old_list[i]}).sort([("count_time",-1)]).limit(1)
                else:
                    if cycleType == "0":#按天  
                        samples_data=col_StatisticsEvent24Hours.find({"old_SensorID":collectorsIDs_old_list[i],"count_time":count_time}).sort([("count_time",-1)]).limit(1)
                    if cycleType == "1":#按天  
                        samples_data=col_StatisticsEvent7Days.find({"old_SensorID":collectorsIDs_old_list[i],"count_time":count_time}).sort([("count_time",-1)]).limit(1)
                    if cycleType == "2":#按天  
                        samples_data=col_StatisticsEvent30Days.find({"old_SensorID":collectorsIDs_old_list[i],"count_time":count_time}).sort([("count_time",-1)]).limit(1)
                for item_2 in samples_data:
                    no_data_flag = 0
                    if count_time == "":
                        count_time = item_2["count_time"]
                        EndTimeList=item_2["EndTimeList"]
                        BeginTimeList=item_2["BeginTimeList"]
                        
                    if len(peakLimitEvent) < 1:
                        peakLimitEvent=item_2["peakLimitEvent"]
                    else:
                        print("befor peakLimitEvent length is:" + str(len(peakLimitEvent)) + "  current peakLimitEvent length is:" + str(len(item_2["peakLimitEvent"])) )
                        peakLimitEvent=list_add(peakLimitEvent,item_2["peakLimitEvent"])
                        
                    if len(vibrationLimit1Event) < 1:
                        vibrationLimit1Event=item_2["vibrationLimit1Event"]
                    else:
                        print("befor vibrationLimit1Event length is:" + str(len(vibrationLimit1Event)) + "  current vibrationLimit1Event length is:" + str(len(item_2["vibrationLimit1Event"])) )
                        vibrationLimit1Event=list_add(vibrationLimit1Event,item_2["vibrationLimit1Event"])
                        
                    if len(vibrationLimit2Event) < 1:
                        vibrationLimit2Event=item_2["vibrationLimit2Event"]
                    else:
                        print("befor vibrationLimit2Event length is:" + str(len(vibrationLimit2Event)) + "  current vibrationLimit2Event length is:" + str(len(item_2["vibrationLimit2Event"])) )
                        vibrationLimit2Event=list_add(vibrationLimit2Event,item_2["vibrationLimit2Event"])
                if isinstance(samples_data,str):
                    samples_data = ""
                else:
                    samples_data.close()
            
            item1={"workPointID":WorkPointID,\
                     "workPointName":"",\
                     "EndTimeList":EndTimeList,\
                     "BeginTimeList":BeginTimeList,\
                     "peakLimitEvent":peakLimitEvent,\
                     "vibrationLimit1Event":vibrationLimit1Event,\
                     "vibrationLimit2Event":vibrationLimit2Event}
            if no_data_flag != 0:
                samples_data=""
                EndTimeList=[]
                BeginTimeList=[]
                if cycleType == "0":#按天  
                    samples_data=col_StatisticsEvent24Hours.find().sort([("count_time",-1)]).limit(1)
                if cycleType == "1":#按天  
                    samples_data=col_StatisticsEvent7Days.find().sort([("count_time",-1)]).limit(1)
                if cycleType == "2":#按天  
                    samples_data=col_StatisticsEvent30Days.find().sort([("count_time",-1)]).limit(1)
                for item_2 in samples_data:
                    EndTimeList=item_2["EndTimeList"]
                    BeginTimeList=item_2["BeginTimeList"]
                item1['workPointID']=WorkPointID
                item1['EndTimeList']=EndTimeList
                item1['BeginTimeList']=BeginTimeList
                item1['peakLimitEvent']=[]
                item1['vibrationLimit1Event']=[]
                item1['vibrationLimit2Event']=[]
                if isinstance(samples_data,str):
                    samples_data = ""
                else:
                    samples_data.close()
            resultList.append(item1)
    return resultList

class GetWorkPointEventNumber4CycleTime_tempHandler(BaseHandler):
    def get(self):
        #resultList=[]
        workPointIDs = self.get_argument('workPointIDs')
        cycleType = self.get_argument('cycleType')
        print(workPointIDs)
        print(cycleType)
        print("===============")
        workPointID_list=workPointIDs.split(",")
        print(workPointID_list)
        
        resultList = GetWorkPointEventNumber4Cycle(workPointID_list, cycleType)
       
        
        #EndTimeList=[]
        #BeginTimeList=[]
        #peakLimitEvent=[]
        #vibrationLimit1Event=[]
        #vibrationLimit2Event=[]
        
        ####for WorkPointID in workPointID_list:
        ####    result_sensorIDs = findOldsensorIDbyWorkPointID(WorkPointID)
        ####    collectorsIDs_old_list = result_sensorIDs['collectorsIDs_old']
        ####    print(collectorsIDs_old_list)
        ####    
        ####    count_time = ""
        ####    EndTimeList=[]
        ####    BeginTimeList=[]
        ####    peakLimitEvent=[]
        ####    vibrationLimit1Event=[]
        ####    vibrationLimit2Event=[]
        ####    
        ####    for i in range(len(collectorsIDs_old_list)):
        ####        print(collectorsIDs_old_list[i])
        ####        samples_data=""
        ####        #if cycleType == "0":#按天                    
        ####        if count_time == "":
        ####            if cycleType == "0":#按天  
        ####                samples_data=col_StatisticsEvent24Hours.find({"old_SensorID":collectorsIDs_old_list[i]}).sort([("count_time",-1)]).limit(1)
        ####            if cycleType == "1":#按天  
        ####                samples_data=col_StatisticsEvent7Days.find({"old_SensorID":collectorsIDs_old_list[i]}).sort([("count_time",-1)]).limit(1)
        ####            if cycleType == "2":#按天  
        ####                samples_data=col_StatisticsEvent30Days.find({"old_SensorID":collectorsIDs_old_list[i]}).sort([("count_time",-1)]).limit(1)
        ####        else:
        ####            if cycleType == "0":#按天  
        ####                samples_data=col_StatisticsEvent24Hours.find({"old_SensorID":collectorsIDs_old_list[i],"count_time":count_time}).sort([("count_time",-1)]).limit(1)
        ####            if cycleType == "1":#按天  
        ####                samples_data=col_StatisticsEvent7Days.find({"old_SensorID":collectorsIDs_old_list[i],"count_time":count_time}).sort([("count_time",-1)]).limit(1)
        ####            if cycleType == "2":#按天  
        ####                samples_data=col_StatisticsEvent30Days.find({"old_SensorID":collectorsIDs_old_list[i],"count_time":count_time}).sort([("count_time",-1)]).limit(1)
        ####        for item_2 in samples_data:
        ####            if count_time == "":
        ####                count_time = item_2["count_time"]
        ####                EndTimeList=item_2["EndTimeList"]
        ####                BeginTimeList=item_2["BeginTimeList"]
        ####                
        ####            if len(peakLimitEvent) < 1:
        ####                peakLimitEvent=item_2["peakLimitEvent"]
        ####            else:
        ####                print("befor peakLimitEvent length is:" + str(len(peakLimitEvent)) + "  current peakLimitEvent length is:" + str(len(item_2["peakLimitEvent"])) )
        ####                peakLimitEvent=list_add(peakLimitEvent,item_2["peakLimitEvent"])
        ####                
        ####            if len(vibrationLimit1Event) < 1:
        ####                vibrationLimit1Event=item_2["vibrationLimit1Event"]
        ####            else:
        ####                print("befor vibrationLimit1Event length is:" + str(len(vibrationLimit1Event)) + "  current vibrationLimit1Event length is:" + str(len(item_2["vibrationLimit1Event"])) )
        ####                vibrationLimit1Event=list_add(vibrationLimit1Event,item_2["vibrationLimit1Event"])
        ####                
        ####            if len(vibrationLimit2Event) < 1:
        ####                vibrationLimit2Event=item_2["vibrationLimit2Event"]
        ####            else:
        ####                print("befor vibrationLimit2Event length is:" + str(len(vibrationLimit2Event)) + "  current vibrationLimit2Event length is:" + str(len(item_2["vibrationLimit2Event"])) )
        ####                vibrationLimit2Event=list_add(vibrationLimit2Event,item_2["vibrationLimit2Event"])
        ####        if isinstance(samples_data,str):
        ####            samples_data = ""
        ####        else:
        ####            samples_data.close()
        ####    item1={"workPointID":WorkPointID,\
        ####             "workPointName":"",\
        ####             "EndTimeList":EndTimeList,\
        ####             "BeginTimeList":BeginTimeList,\
        ####             "peakLimitEvent":peakLimitEvent,\
        ####             "vibrationLimit1Event":vibrationLimit1Event,\
        ####             "vibrationLimit2Event":vibrationLimit2Event}
        ####    print(item1)
        ####    resultList.append(item1)
                

        #EndTimeList=[]
        #BeginTimeList=[]
        #peakLimitEvent=[]
        #vibrationLimit1Event=[]
        #vibrationLimit2Event=[]
        #
        #peakLimitEvent_1=[]
        #vibrationLimit1Event_1=[]
        #vibrationLimit2Event_1=[]
        #
        #if cycleType == "0":#按天
        #    samples_data=col_StatisticsEvent24Hours.find({"sensorID":"N19001025","old_SensorID":"01E2C847_01"}).sort([("count_time",-1)]).limit(1)
        #    for item_2 in samples_data:
        #        EndTimeList=item_2["EndTimeList"]
        #        BeginTimeList=item_2["BeginTimeList"]
        #        peakLimitEvent=item_2["peakLimitEvent"]
        #        vibrationLimit1Event=item_2["vibrationLimit1Event"]
        #        vibrationLimit2Event=item_2["vibrationLimit2Event"]
        #    samples_data.close()
        #    
        #    samples_data=col_StatisticsEvent24Hours.find({"sensorID":"N19001027","old_SensorID":"01E2C847_03"}).sort([("count_time",-1)]).limit(1)
        #    for item_2 in samples_data:
        #        peakLimitEvent_1=item_2["peakLimitEvent"]
        #        vibrationLimit1Event_1=item_2["vibrationLimit1Event"]
        #        vibrationLimit2Event_1=item_2["vibrationLimit2Event"]
        #    samples_data.close()
        #    item1={"workPointID":"cddt5_001",\
        #             "workPointName":"5号线神九区间YDK28+900",\
        #             "EndTimeList":EndTimeList,\
        #             "BeginTimeList":BeginTimeList,\
        #             "peakLimitEvent":list_add(peakLimitEvent,peakLimitEvent_1),\
        #             "vibrationLimit1Event":list_add(vibrationLimit1Event,vibrationLimit1Event_1),\
        #             "vibrationLimit2Event":list_add(vibrationLimit2Event,vibrationLimit2Event_1)}
        #    resultList.append(item1)
        #    peakLimitEvent=[149, 134, 118, 120, 139, 147, 126, 188, 190, 160, 124, 110, 121, 129, 138, 142, 130, 141, 109, 107, 156, 177, 190, 159]
        #    vibrationLimit1Event=[23, 19, 20, 22, 20, 22, 22, 29, 33, 25, 19, 21, 23, 20, 22, 19, 18, 13, 18, 19, 23, 26, 30, 25]
        #    vibrationLimit2Event=[23, 19, 19, 22, 20, 21, 22, 23, 29, 24, 18, 21, 23, 20, 21, 19, 18, 12, 17, 18, 22, 26, 28, 25]
        #
        #
        #    item1={"workPointID":"gzsn_001",\
        #             "workPointName":"广州枢纽CK1+100",\
        #             "EndTimeList":EndTimeList,\
        #             "BeginTimeList":BeginTimeList,\
        #             "peakLimitEvent":peakLimitEvent,\
        #             "vibrationLimit1Event":vibrationLimit1Event,\
        #             "vibrationLimit2Event":vibrationLimit2Event}
        #    resultList.append(item1)
        #elif cycleType == "1":#按周
        #    startTime=endTime + timedelta( days = -7 )
        #elif cycleType == "2":#按月
        #    startTime=endTime + timedelta( days = -30 )
            
        data_json = {"resultList":resultList}
        self.write_json(data_json)

class GetWorkPointEventNumber_tempHandler(BaseHandler):
    def get(self):
        resultList=[]
        workPointIDs = self.get_argument('workPointIDs')
        print("==================================================")
        print(workPointIDs)
        workPointID_list=workPointIDs.split(",")
        
        temp_result = GetWorkPointEventNumber4Cycle(workPointID_list, "1")
        temp_resultList = []
        for WorkPointID in workPointID_list:
            result_sensorIDs = findOldsensorIDbyWorkPointID(WorkPointID)
            collectorsIDs_old_list = result_sensorIDs['collectorsIDs_old']
            print(result_sensorIDs)
            peakLimitCount_1=0
            vibrationLimit1_1=0
            vibrationLimit2_1=0
            #print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
            #for i in range(len(collectorsIDs_old_list)):
            #    print(collectorsIDs_old_list[i])
            #    print("-------------------------------------------")
            #    if result_sensorIDs['mqtt_check_list'][i] == 1:
            #        peakLimitCount_1=peakLimitCount_1+col_event_mqtt.find({"sensorID":collectorsIDs_old_list[i],"eventType":1}).count()
            #        vibrationLimit1_1=vibrationLimit1_1+col_event_mqtt.find({"sensorID":collectorsIDs_old_list[i],"eventType":2}).count()
            #        vibrationLimit2_1=vibrationLimit2_1+col_event_mqtt.find({"sensorID":collectorsIDs_old_list[i],"eventType":3}).count()
            #    else:
            #        peakLimitCount_1=peakLimitCount_1+col_event.find({"sensorID":collectorsIDs_old_list[i],"eventType":1}).count()
            #        vibrationLimit1_1=vibrationLimit1_1+col_event.find({"sensorID":collectorsIDs_old_list[i],"eventType":2}).count()
            #        vibrationLimit2_1=vibrationLimit2_1+col_event.find({"sensorID":collectorsIDs_old_list[i],"eventType":3}).count()
                
            item1={"workPointID":WorkPointID,"workPointName":result_sensorIDs['workPointName'],"peakLimitCount":peakLimitCount_1,\
               "vibrationLimit1":vibrationLimit1_1,"vibrationLimit2":vibrationLimit2_1}
            temp_resultList.append(item1)
            
        for resultList_item in temp_resultList:
            for temp_result_item in temp_result:
                if resultList_item['workPointID'] == temp_result_item['workPointID']:
                    resultList_item['peakLimitCount']=sum(temp_result_item['peakLimitEvent'])
                    resultList_item['vibrationLimit1']=sum(temp_result_item['vibrationLimit1Event'])
                    resultList_item['vibrationLimit2']=sum(temp_result_item['vibrationLimit2Event'])
                    resultList.append(resultList_item)
            
        #print("================================temp_result is:")
        #print(temp_result)
        #print("================================resultList is:")
        #print(resultList)
        data_json = {"workPointList":resultList}
        self.write_json(data_json)